package page;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

/**
 * Servlet implementation class ConnexionServlet
 */
public class ConnexionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ConnexionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dis;
		
		HttpSession session=request.getSession();
		if(session.getAttribute("user_id") == null)
			dis=request.getRequestDispatcher("login.jsp");
		else
			dis=request.getRequestDispatcher("unlogin.jsp");
		
		dis.forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		Connection con = null;

		if(request.getParameter("unlogin") != null && request.getParameter("unlogin").equals("Oui")) {
			session.invalidate();
		}
		else
		{
			try{
				Context namingContext = new InitialContext();
				DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
				con = dataSource.getConnection();
				
				PreparedStatement pstmt=con.prepareStatement("SELECT m.id_membre, m.pseudo FROM membre m WHERE m.pseudo = ? AND m.password = ?");
				pstmt.setString(1, request.getParameter("pseudo"));
				pstmt.setString(2, request.getParameter("password"));
				ResultSet rs = pstmt.executeQuery();
				
				while(rs.next()){
					session.setAttribute("user_id", rs.getInt("id_membre"));
					session.setAttribute("username", rs.getString("pseudo"));
				}
				
				rs.close();
				
			}catch(Exception e){
				System.out.println("Erreur lors du login : "+e);
			} finally {
				try {
					if(con != null) con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		RequestDispatcher dis;
		dis=request.getRequestDispatcher("home");
		dis.forward(request,response);
	}
}
